from rest_framework import serializers
from .models import Event, Calendar


class EventSerializer(serializers.ModelSerializer):
    period_display = serializers.CharField(source='get_period_display', read_only=True)
    importance_display = serializers.CharField(source='get_importance_display', read_only=True)
    status_display = serializers.CharField(source='get_status_display', read_only=True)
    time_range = serializers.SerializerMethodField()

    class Meta:
        model = Event
        fields = [
            'id', 'title', 'description', 'date', 'start_time', 'end_time',
            'time_range', 'period', 'period_display', 'importance',
            'importance_display', 'status', 'status_display', 'creator_id',
            'location', 'reminder', 'reminder_time', 'related_note_id'
        ]
        read_only_fields = ['period', 'creator_id']

    def get_time_range(self, obj):
        """获取时间范围字符串"""
        return f"{obj.start_time.strftime('%H:%M')} - {obj.end_time.strftime('%H:%M')}"

    def create(self, validated_data):
        """创建时自动关联当前用户"""
        user = self.context['request'].user
        instance = super().create(validated_data)
        instance.related_users.add(user)
        return instance


class CalendarSerializer(serializers.ModelSerializer):
    events_count = serializers.IntegerField(source='get_events_count', read_only=True)
    completed_count = serializers.IntegerField(source='get_completed_count', read_only=True)

    class Meta:
        model = Calendar
        fields = ['id', 'date', 'year', 'month', 'events_count', 'completed_count']